package com.qzyh.esb.egsa.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qzyh.esb.egsa.bean.vo.DeptTreeVO;
import com.qzyh.esb.egsa.entity.Dept;
import com.qzyh.esb.egsa.mapper.DeptMapper;
import com.qzyh.esb.egsa.service.IDeptService;
import com.qzyh.esb.egsa.utils.DeptConverter;
import com.qzyh.esb.egsa.utils.ResultObject;
import com.qzyh.esb.egsa.utils.TreeBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.List;

/**
 * <p>
 * 部门表 服务实现类
 * </p>
 *
 * @author whq
 * @since 2023-03-16
 */
@Service
public class DeptServiceImpl extends ServiceImpl<DeptMapper, Dept> implements IDeptService {

    @Autowired
    private DeptMapper deptMapper;

    @Override
    public List<DeptTreeVO> getList(String deptName) {
        QueryWrapper<Dept> wrapper = Wrappers.query();
        if (StringUtils.hasLength(deptName)){
            wrapper.like("dept_name", deptName);
        }
        wrapper.orderByAsc("dept_sort+1");
        List<Dept> deptList = deptMapper.selectList(wrapper);
        List<DeptTreeVO> deptTreeVOList = DeptConverter.INSTANCE.deptListToDeptTreeVOList(deptList);
        return TreeBuilder.buildTree(deptTreeVOList);
    }

    @Override
    @Transactional
    public ResultObject deleteById(String id) {
        //判断该id是否为父级菜单，父级菜单不允许直接删除
        QueryWrapper<Dept> wrapper = Wrappers.query();
        wrapper.eq("parent_id", id);
        List<Dept> deptList = deptMapper.selectList(wrapper);
        if (deptList!=null && deptList.size()>0){//查询数据不为空
            return ResultObject.fail("该部门为上级部门，不允许直接删除，请先删除该部门的下级部门");
        }
        deptMapper.deleteById(id);
        return ResultObject.success("删除成功");
    }

    public List<String> getFatherTree(List<DeptTreeVO> list, String id){
        return TreeBuilder.getFatherTree(list,id);
    }

    @Override
    public List<Dept> queryByName(String deptName) {
        if (StringUtils.hasLength(deptName)){
            QueryWrapper<Dept> wrapper = Wrappers.query();
            wrapper.like("dept_name", deptName);
            wrapper.orderByAsc("dept_sort+1");
            return deptMapper.selectList(wrapper);
        }
        return null;
    }

    @Override
    public List<Dept> queryByIds(String idsStr) {
        if (StringUtils.hasLength(idsStr)){
            QueryWrapper<Dept> wrapper = Wrappers.query();
            String[] idArray = idsStr.split(",");
            for (int i = 0; i < idArray.length; i++) {
                wrapper.eq("id", idArray[i]).or();
            }
            wrapper.orderByAsc("dept_sort+1");
            return deptMapper.selectList(wrapper);
        }
        return null;
    }
}
